package servlet;

import dao.UserinfoDao;
import entity.Userinfo;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * 注册
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取请求参数
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String gender = req.getParameter("gender");
        String nickname = req.getParameter("nickname");
        String autograph = req.getParameter("autograph");
        String password = req.getParameter("password");

        Userinfo user = new Userinfo(null, username, gender, nickname, autograph, password);
        System.out.println(user);

        //2.向数据库中添加数据
        UserinfoDao userinfoDao = new UserinfoDao();
        JSONObject resData = new JSONObject();
        resData.put("code", 200);

        try {
            boolean b = userinfoDao.addUser(user);
            resData.put("msg", b ? "注册成功" : "注册失败");
        } catch (SQLException e) {
            resData.put("msg", "注册失败，用户名已存在");
        }

        //3.响应数据给前端
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.println(resData);
        writer.flush();
        writer.close();

    }
}
